package com.offcn.play.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.offcn.play.service.PayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class PayServiceImpl implements PayService {
    @Autowired
    private AlipayClient alipayClient;

    /**
     * 生成支付宝二维码
     *
     * @param out_trade_no
     * @param total_amount
     * @return
     */
    @Override
    public Map createCode(String out_trade_no, String total_amount) {
        Map<String, String> map = new HashMap<>();
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", out_trade_no);
        bizContent.put("total_amount", total_amount);
        bizContent.put("subject", "测试商品");
        request.setBizContent(bizContent.toString());

        try {
            AlipayTradePrecreateResponse response = alipayClient.execute(request);

            String code = response.getCode();
            String body = response.getBody();
            //接口调用成功，调用结果请参考具体的 API 所对应的业务返回参数
            if (code.equals("10000")) {
                map.put("qrcode", response.getQrCode());
                map.put("out_trade_no", response.getOutTradeNo());
                map.put("total_fee", total_amount);
            } else {
                System.out.println("预下单，接口调用失败" + body);
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return map;
    }

    /**
     * 查询支付状态
     */
    @Override
    public Map queryPayStatus(String out_trade_no) {

        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        Map<String, String> map = new HashMap<>();

        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", out_trade_no);
        request.setBizContent(bizContent.toString());


        try {
            AlipayTradeQueryResponse response = alipayClient.execute(request);

            String code = response.getCode();
            if (code.equals("10000")) {
                map.put("out_trade_no", response.getOutTradeNo());
                map.put("tradeStatus", response.getTradeStatus());
                //支付包的交易流水号码
                map.put("trade_no", response.getTradeNo());
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return map;
    }
}
